//
//  OrderClosingManager.m
//  YueYueSpecailCarDriver
//
//  Created by 李亚军 on 2017/6/28.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "OrderClosingManager.h"
#import "BaseNavigationController.h"
#import "NotificationNameManager.h"
#import "BaseViewController.h"
#import <QXYueYueModels/QXYueYueModels-umbrella.h>
#import "HeaderMacro.h"
#import "DLLApiManager.h"
#import "ongoingOrdersViewController.h"
#import "orderDetailsViewController.h"
#import "paymentOrderDetailsViewController.h"
#import "progressOrderDetailsViewController.h"
#import "endTheTripViewController.h"
#import "carEndTheTripViewController.h"


@interface OrderClosingManager ()

/// 正在进行中的订单id
@property(nonatomic , copy) NSString *onGogingOrderUuid;

/// 根视图导航栏
@property(nonatomic , strong) UINavigationController *naviVC;

/// 跟视图
@property(nonatomic , strong) BaseViewController *baseVC;

@property(nonatomic , copy) void(^receivedNotification)(NSNotification *);

/// 如果相应了页面跳转,这位nil,发起跳转设置订单uuid,目的防止后台长连接推送多次
@property(nonatomic , copy) NSString *respondUuid;

@end

static OrderClosingManager *manager = nil;
@implementation OrderClosingManager

+ (OrderClosingManager *)shareManager {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [OrderClosingManager new];
    });
    
    manager.naviVC = [BaseViewController baseNavigationController];
    
    return manager;
}

- (void)openNotificationWithOrderUuid:(NSString *)orderUuid receivedNotification:(void (^)(NSNotification *))aNotification {
    
    if (orderUuid) {
        
        self.onGogingOrderUuid = orderUuid;
        self.receivedNotification = aNotification;
        self.respondUuid = nil;
        
        [self registerNotification];
        
    }else {
        
        [self closeNotification];
    }
}

- (void)closeNotification {
    
    self.onGogingOrderUuid = nil;
    self.respondUuid = nil;
    self.receivedNotification = nil;
    [self cancelNotification];
}

#pragma mark - 注册订单被改派的通知

- (void)registerNotification {
    // 注册订单被改派的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderClosingAction:) name:NotificationName_LongLink_OrderChanged object:nil];
    // 注册订单被后台关闭的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderClosingAction:) name:NotificationName_LongLink_BackShutDownOrder object:nil];
    // 注册乘客取消订单通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderClosingAction:) name:NotificationName_LongLink_PassengerCancelOrder object:nil];
}

- (void)orderClosingAction:(NSNotification *)aNotification {
    
    if (self.onGogingOrderUuid == nil) {
        
        NSLog(@"需要开启通知,使用方法 openNotificationWithOrderUuid:");
    }
    
    if (aNotification.object != nil) {
        
        NSDictionary *dataDic = aNotification.object[@"data"];
        NSString *orderUuid = dataDic[@"orderUuid"];
        if (orderUuid != nil) {
            
            if ([self.onGogingOrderUuid isEqualToString:orderUuid]) { // 如果收到的通知与当前的进行中订单的Uuid相同,那么执行
                
                if ([aNotification.name isEqualToString:NotificationName_LongLink_PassengerCancelOrder]) {
                    
                    
                    [self orderChangedByPassenger:self.onGogingOrderUuid];
                }
                
                if ([aNotification.name isEqualToString:NotificationName_LongLink_BackShutDownOrder]) {
                    
                    
                    [self orderShutedDownByService:self.onGogingOrderUuid];
                }
                
                if ([aNotification.name isEqualToString:NotificationName_LongLink_OrderChanged]) {
                    
                    
                    [self orderChangedAction:aNotification];
                }
                
                if (self.receivedNotification) {
                    
                    self.receivedNotification(aNotification);
                }
            }
        }
    }
}

#pragma mark - 订单被乘客取消
/// 订单被乘客取消
- (void)orderChangedByPassenger:(NSString *)orderUuid {
    
    if (self.respondUuid == nil) {
        
        self.respondUuid = orderUuid;
        [self getOrdersDetailsWithOrderUuid:orderUuid];
    }
    
}

#pragma mark - 订单被后台关闭
/// 订单被后台关闭
- (void)orderShutedDownByService:(NSString *)orderUuid {
    
    if (self.respondUuid == nil) {
        
        self.respondUuid = orderUuid;
        [self getOrdersDetailsWithOrderUuid:orderUuid];
    }
}

#pragma mark - 订单被改派
/// 订单被改派
- (void)orderChangedAction:(NSNotification *)aNotification {
    
    __weak typeof(self) weakSelf = self;
    NSString *title = @"";
    
    if ([[aNotification.object allKeys] containsObject:@"data"]) {
        
        title = aNotification.object[@"data"][@"title"];
    }
    NSString *warningStr;
    
    if ([[aNotification.object allKeys] containsObject:@"data"]) {
        
        warningStr = aNotification.object[@"data"][@"content"];
    }
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:warningStr preferredStyle:(UIAlertControllerStyleAlert)];
    
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf.naviVC popToRootViewControllerAnimated:YES];
        strongSelf.naviVC = nil;
    }]];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (self.respondUuid == nil) {
            
            self.respondUuid = aNotification.object[@"data"][@"orderUuid"];
            [self.naviVC presentViewController:alertVC animated:YES completion:^{
                
                
            }];
        }
        
    });
    
}

#pragma mark - 从新获取最新的订单详情
/// 订单状态发生改变收到通知后拉去订单详情,进行跳转
- (void)getOrdersDetailsWithOrderUuid:(NSString *)orderUuid {
    
    __weak typeof(self) weakSelf = self;

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:orderUuid forKey:@"orderUuid"];
    [DLLApiManager getTheOrderDetailsWithParameters:dic success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        
        if (NetWork_Success) {
            
            QXYYOrderDetailModel *ordersDetailsModel = [QXYYOrderDetailModel QXYY_objectWithKeyValues:data[@"data"]];
            QXYYUserPassengerModel *userPassengerModel = [QXYYUserPassengerModel QXYY_objectWithKeyValues:data[@"data"][@"passenger"]];
            
            [strongSelf dealOrderDetailWithStateNumber:ordersDetailsModel.subStatus OrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel];
            
        }
        
    } failure:^(NSError *error) {

    }];
}


#pragma mark - 如果订单被关闭,根据获取的最新订单信息,跳转到对应的页面
/**
 根据订单状态处理不同的结果(进入不同的详情页面)
 */
- (void)dealOrderDetailWithStateNumber:(NSInteger)stateNumber OrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    switch (stateNumber) {
        
        // 未开始
        case OrderStatusEnumCode_DriverReceivedOrder_DetermineStroke: // 200 行程未开始,预约订单
        {
            [self pushIntoOrdersDetailsViewControllerWithStateNumber:stateNumber OrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel];
            break;
        }
            
        // 行程中
        case OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers: // 210［去接乘客］司机出发、去接乘客 . ［出租／专车］
        case OrderStatusEnumCode_DriverArrived_WaitingForPassengers: // 220［等待乘客］司机到达、等待乘客 . ［出租／专车
        case OrderStatusEnumCode_PickedUpPasengers_StrokeStart: // 进行中  300：［行程开始］乘客上车、行程开始 . ［出租／专车／拼车］
        {
            
            [self pushIntoongoingOrdersViewControllerWithStateNumber:stateNumber OrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel];
            break;
        }
        
        // 等待司机确认费用
        case OrderStatusEnumCode_PassengersArrivedDestination: // 400：［行程结束］司机送达目的地 ,这时候显示催款,提现页面
        {
            [self pushIntoendTheTripViewControllerWithStateNumber:stateNumber OrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel];
            break;
        }
            
        
        // 催款
        case OrderStatusEnumCode_DriverConfirmFare_WaitingForPassengersToPay: // 500：司机确认费用，等待乘客支付
        case OrderStatusEnumCode_StrokeDetermination_PassengerCancelOrder_WaitingForPassengersToPayCancleFare: // 511：［行程确定］乘客取消，待支付取消费用
        case OrderStatusEnumCode_StrokeDetermination_DriverCancelOrder_WaitingForPassengersToPayCancleFare: // 521：［行程确定］司机取消，待支付取消费用
        case OrderStatusEnumCode_GotoPickUpPassengers_PassengerCancelOrder_WaitingForPassengersToPayCancleFare: // 512：［去接乘客］乘客取消，待支付取消费用
        case OrderStatusEnumCode_GotoPickUpPassengers_DriverCancelOrder_WaitingForPassengersToPayCancleFare: // 522：［去接乘客］司机取消，待支付取消费用
        case OrderStatusEnumCode_WaitingForPassengers_PassengerCancelOrder_WaitingForPassengersToPayCancleFare: // 513：［等待乘客］乘客取消，待支付取消费用
        case OrderStatusEnumCode_WaitingForPassengers_DriverCancelOrder_WaitingForPassengersToPayCancleFare: // 523：［等待乘客］司机取消，待支付取消费用
        {
            
            [self pushIntopaymentOrderDetailsViewControllerWithStateNumber:stateNumber OrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel];
            break;
        }
            
        // 支付完成,订单结束
        case OrderStatusEnumCode_PaymentCompleted_StrokeOver: // 600：付款完成、行程结束 , 不显示催款,提现页面
        case OrderStatusEnumCode_PassengersHasCompletedEvaluationForDriver: // 610：乘客完成对车主评价 , 不显示催款,提现页面
        {
            
            [self pushIntopaymentOrderDetailsViewControllerWithStateNumber:stateNumber OrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel];
            break;
        }
            
        // 处理无费用的取消订单
        case OrderStatusEnumCode_NewStroke_PassengerCancel: // 900：［新行程］乘客取消
        case OrderStatusEnumCode_PassengersCancel_StrokeDetemination_DriverNotArrive: // 901: 乘客取消（行程确定后、司机未到达
        case OrderStatusEnumCode_PassengersCancel_StrokeDetemination_DriverArrived: // 902: 乘客取消（行程确定后、司机到达）
        case OrderStatusEnumCode_NewStroke_DriverCancel: // 910：［新行程］司机取消
        case OrderStatusEnumCode_NoFare_StrokeDetermination_PassengersCancelOrder: // 90200：［无费用］［行程确定］乘客取消订单
        case OrderStatusEnumCode_NoFare_GotoPickUpPassengers_PassengersCancelOrder: // 90210：［无费用］［去接乘客］乘客取消订单
        case OOrderStatusEnumCode_NoFare_WaitingForPassengers_PassengersCancelOrder: // 90220：［无费用］［等待乘客］乘客取消订单
        case OrderStatusEnumCode_NoFare_StrokeDetermination_DriverCancelOrder: // 91200：［无费用］［行程确定］司机取消订单
        case OrderStatusEnumCode_NoFare_GotoPickUpPassengers_DriverCancelOrder: // 91210：［无费用］［去接乘客］司机取消订单
        case OrderStatusEnumCode_NoFare_WaitingForPassengers_DriverCancelOrder: // 91220：［无费用］［等待乘客］司机取消订单
        case OrderStatusEnumCode_OrderClosedByCustomerService: // 990：客服关闭订单
        {
            
            [self pushIntoOrdersDetailsViewControllerWithStateNumber:stateNumber OrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel];
            break;
        }
            
            
        // 处理有费用的取消订单
        case OrderStatusEnumCode_HaveFare_StrokeDetermination_PassengersCancelOrder: // 90511：［有费用］［行程确定］乘客取消订单
        case OrderStatusEnumCode_HaveFare_GotoPickUpPassengers_PassengersCancelOrder: // 90512：［有费用］［去接乘客］乘客取消订单
        case OrderStatusEnumCode_HaveFare_WaitingForPassengers_PassengersCancelOrder: // 90513：［有费用］［等待乘客］乘客取消订单
        case OrderStatusEnumCode_HaveFare_StrokeDetermination_DriverCancelOrder: // 91521：［有费用］［行程确定］司机取消订单
        case OrderStatusEnumCode_HaveFare_GotoPickUpPassengers_DriverCancelOrder: // 91522：［有费用］［去接乘客］司机取消订单
        case OrderStatusEnumCode_HaveFare_WaitingForPassengers_DriverCancelOrder: // 91523：［有费用］［等待乘客］司机取消订单
        {
            [self pushIntopaymentOrderDetailsViewControllerWithStateNumber:stateNumber OrdersDetailsModel:ordersDetailsModel UserPassengerModel:userPassengerModel]; // 这里显示支付的费用
            break;
        }
            
        default:
            break;
    }
}




/**
 进入正在进行的订单页面 , 去接乘客,到达目的地,乘客已上车,前往目的地
 Code:
 210：［去接乘客］司机出发、去接乘客
 220：［等待乘客］司机到达、等待乘客
 300：［行程开始］乘客上车、行程开始
 */
- (void)pushIntoongoingOrdersViewControllerWithStateNumber:(NSInteger)stateNumber OrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    ongoingOrdersViewController *vc = [ongoingOrdersViewController shareSelf];
    vc.ordersDetailsModel = ordersDetailsModel;
    vc.userPassengerModel = userPassengerModel;
    
    
    dispatch_async(dispatch_get_main_queue(), ^{   // 抢到实时单后进入订单详情
        
        [self.naviVC pushViewController:vc animated:YES];
        self.respondUuid = nil;
    });
}


/**
 进入订单详情,拨打客服电话,投诉
 Code:
 200：［行程确定］司机接单、行程确定 (预约单的状态,即时单没有这个状态)
 600：付款完成、行程结束
 610：乘客完成对车主评价
 900：［新行程］乘客取消
 901:  乘客取消（行程确定后、司机未到达）
 902:  乘客取消（行程确定后、司机到达）
 910: ［新行程］司机取消
 90200：［无费用］［行程确定］乘客取消订单
 90210：［无费用］［去接乘客］乘客取消订单
 90220：［无费用］［等待乘客］乘客取消订单
 91200：［无费用］［行程确定］司机取消订单
 91210：［无费用］［去接乘客］司机取消订单
 91220：［无费用］［等待乘客］司机取消订单
 
 90511：［有费用］［行程确定］乘客取消订单
 90512：［有费用］［去接乘客］乘客取消订单
 90513：［有费用］［等待乘客］乘客取消订单
 91521：［有费用］［行程确定］司机取消订单
 91522：［有费用］［去接乘客］司机取消订单
 91523：［有费用］［等待乘客］司机取消订单
 990：客服关闭订单
 */
- (void)pushIntoOrdersDetailsViewControllerWithStateNumber:(NSInteger)stateNumber OrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    orderDetailsViewController *orderDetailVC = [orderDetailsViewController shareSelf];
    orderDetailVC.title = @"订单详情";
    orderDetailVC.ordersDetailsModel = ordersDetailsModel;
    orderDetailVC.userPassengerModel = userPassengerModel;
    orderDetailVC.isPoPToRootVC = YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.naviVC pushViewController:orderDetailVC animated:YES];
        self.respondUuid = nil;
    });
    
}


/**
 进入结算页面,确认费用
 Code:
 400：［行程结束］司机送达目的地
 */
- (void)pushIntoendTheTripViewControllerWithStateNumber:(NSInteger)stateNumber OrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    if ([ordersDetailsModel.typeTrip integerValue] == 1) {
        
        endTheTripViewController *endTheTripVC = [endTheTripViewController shareSelf];
        endTheTripVC.title = @"结算";
        endTheTripVC.userPassengerModel = userPassengerModel;
        endTheTripVC.ordersDetailsModel = ordersDetailsModel;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.naviVC pushViewController:endTheTripVC animated:YES];
            self.respondUuid = nil;
        });
        
    }else {
        
        carEndTheTripViewController *vc = [carEndTheTripViewController shareSelf];
        vc.ordersDetailsModel = ordersDetailsModel;
        vc.userPassengerModel = userPassengerModel;
        vc.title = @"结算";
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.naviVC pushViewController:vc animated:YES];
            self.respondUuid = nil;
        });
        
    }
}


/**
 进入催款详情页面页面
 Code:
 500：司机确认费用，等待乘客支付
 511：［行程确定］乘客取消，待支付取消费用
 521：［行程确定］司机取消，待支付取消费用
 512：［去接乘客］乘客取消，待支付取消费用
 522：［去接乘客］司机取消，待支付取消费用
 513：［等待乘客］乘客取消，待支付取消费用
 523：［等待乘客］司机取消，待支付取消费用
 */
- (void)pushIntopaymentOrderDetailsViewControllerWithStateNumber:(NSInteger)stateNumber OrdersDetailsModel:(QXYYOrderDetailModel *)ordersDetailsModel UserPassengerModel:(QXYYUserPassengerModel *)userPassengerModel {
    
    paymentOrderDetailsViewController *paymentOrderDetailVC = [paymentOrderDetailsViewController shareSelf];
    paymentOrderDetailVC.title = @"订单详情";
    paymentOrderDetailVC.userPassengerModel = userPassengerModel;
    paymentOrderDetailVC.ordersDetailsModel = ordersDetailsModel;
    paymentOrderDetailVC.isPoPToRootVC = YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.naviVC pushViewController:paymentOrderDetailVC animated:YES];
        self.respondUuid = nil;
    });
    
}




#pragma mark - 注销通知
/// 注销通知
- (void)cancelNotification {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_LongLink_OrderChanged object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_LongLink_BackShutDownOrder object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_LongLink_PassengerCancelOrder object:nil];
}


/*
 * 消息格式实例
     LongLinkNoftificationName_PassengerCancelOrder; object = {
         appId = 9dd58b6d5f64a22d00c3f6264f8ce597;
         createTime = 1498701772516;
         data =     {
             content = "\U4e58\U5ba2\U5df2\U53d6\U6d88\U8ba2\U5355";
             orderType = 2;
             orderUuid = d57d434998754602ac54208dd812277f;
             title = "\U884c\U7a0b\U5df2\U53d6\U6d88";
         };
         needJPush = 0;
         opCode = 2002;
         pushUuid = 869f18f917244a768cc96f6ef5aca956;
         retry = 0;
         to = DRIVER;
     }}
 */

@end
